package org.twnmayberry.jpa;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.twnmayberry.bo.Activity;
import org.twnmayberry.bo.Type;
import org.twnmayberry.dao.ActivityDAO;

public class ActivityDAOImpl implements ActivityDAO {

	private static Log log = LogFactory.getLog(ActivityDAOImpl.class);
	private EntityManager em;
	
	public ActivityDAOImpl(EntityManager man) {
		em = man;
	}
	
	/**
	 * Used this method instead of em.find since it wouldnt return null if Activity wasnt there
	 */
	@Override
	public Activity getActivityByID(long id) {
		Activity results = null;
		results = em.find(Activity.class, id);
		return results;
	}

	@Override
	public List<Activity> getActivitiesByType(Type type) {
		Query query = em.createQuery("Select a from Activity as a where Type = '" + type.ordinal() + "'");
		List<Activity> resultActivities = new ArrayList<Activity>();
		for(Object entry : query.getResultList()) {
			Activity results = (Activity)entry;
			resultActivities.add(results);
		}
		return resultActivities;
	}

	@Override
	public void createActivity(Activity newActive) {
		
		em.persist(newActive);
	}

	@Override
	public boolean deleteActivity(Activity deadActive) {
		em.remove(em.find(Activity.class, deadActive.getId()));
		return true;
	}

	@Override
	public long purgeActivities() {
		int results = 0;
		for(Activity person : getAllActivities()) {
			em.remove(person);
			results++;
		}
		return results;
	}

	@Override
	public void setEntityManager(EntityManager em) {
		this.em = em;
	}

	
	private List<Activity> getAllActivities() {
		List<Activity> createQuery = em.createQuery("select p from Activity p", Activity.class).getResultList();
		return createQuery;
	}
}
